package com.xh.xyzp.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: xianghao
 * @Description:
 * @Date: 2024-10-12  16:15
 */
@Slf4j
public class RedisUtil {

    private static StringRedisTemplate stringRedisTemplate;

    static {
        RedisUtil.stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
    }

    public static String get(String key) {
        return key == null ? null : stringRedisTemplate.opsForValue().get(key);
    }


    public static void delBatch(List<String> keys) {
        stringRedisTemplate.delete(keys);
    }

    public static void del(String key) {
        stringRedisTemplate.delete(key);
    }



    public static Boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                stringRedisTemplate.opsForValue().set(key, objToStr(value), time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Boolean set(String key, Object value, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                stringRedisTemplate.opsForValue().set(key, objToStr(value), time, timeUnit);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Boolean set(String key, Object value) {
        try {
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String objToStr(Object o) {
        return JSONUtil.toJsonStr(o);
    }


}
